<?php

namespace addons\formdesign\library;

use addons\formdesign\library\Formdesign;
use addons\formdesign\library\Formsafe;
use think\Db;

class FormDesignApi extends \think\Controller
{

    protected $form;
    protected $formdesign;
    protected $_obj_model = null;

    public $dataTableName = '';

    public function __construct($form_id = 0, $data_id = 0)
    {
        if ($form_id > 0) {
            $this->form = \app\common\model\formdesign\Form::get($form_id);
            if (!$this->form) {
                $this->error("未找到表单");
            } else {
                $this->formdesign = new Formdesign();
                $this->dataTableName = config('database.prefix') . 'formdesign_form_data_' . $form_id;
            }
        } else {
            $foreign = $this->getForeign($data_id);
            if (!$foreign) {
                $this->error("未找到表单数据");
            } else {
                $this->__construct($foreign['form_id']);
            }
        }
    }

    public function _initialize()
    {
        parent::_initialize();
        Formsafe::safe_gpc();
    }

    /**
     * 返回当前表单数据表模型
     * @return object
     */
    protected function model()
    {
        if ($this->_obj_model) {
            return $this->_obj_model;
        }

        return $this->_obj_model = db('formdesign_form_data_' . $this->form['id']);
    }
    /**
     * 返回数据存储表的状态
     * @return bool
     */
    public function dataReady()
    {
        if (Db::query("SELECT table_name FROM information_schema.TABLES WHERE table_name ='" . $this->dataTableName . "'")) {
            return true;
        }
        return false;
    }

    /**
     * 获取表单基本信息
     * @return array
     */
    public function getForm()
    {
        if ($this->form['status'] !== 'normal') {
            $this->form['html'] = '<<表单未启用>>';
        }
        return $this->form;
    }

    /**
     * 返回前台调用URL地址
     * @param string $form_id 表单ID
     * @return bool
     */
    public function getURL($form_id = null)
    {
        return url('/index/formdesign/Foreign/index', ['form_id' => $form_id ?: $this->form['id']]);
    }

    /**
     * 添加数据的表单HTML代码
     * 支持链式操作
     * @return $this
     */
    public function add()
    {
        $this->form['html'] = $this->formdesign->unparse_form($this->form, [], 'add');
        return $this;
    }

    /**
     * 编辑数据的表单HTML代码
     * 支持链式操作
     * @return $this
     */
    public function edit($id)
    {
        $data = $this->getData($id);
        $this->form['foreign'] = $this->getForeign($id);
        $this->form['html'] = $this->formdesign->unparse_form($this->form, $data, 'edit');
        return $this;
    }

    /**
     * 预览数据的表单HTML代码
     * 支持链式操作
     * @return $this
     */
    public function view($id)
    {
        $data = $this->getData($id);
        $this->form['foreign'] = $this->getForeign($id);
        $this->form['html'] = $this->formdesign->unparse_form($this->form, $data, 'view');
        return $this;
    }


    /**
     * 销毁当前表单所有数据
     * @return bool
     */
    public function destroy()
    {
        $form_id = $this->form['id'];
        \app\common\model\formdesign\Foreign::where('form_id', $form_id)->delete();
        // 启动事务
        Db::startTrans();
        try {
            $this->model()->query('DROP TABLE ' . $this->dataTableName);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }
        return $this->form->delete();
    }

    /**
     * 返回数据的表单HTML代码
     * @return string
     */
    public function output()
    {
        return $this->form['html'];
    }

    /**
     * 返回当前表单的数据列表
     * @return array
     */
    public function getList($where = null, $sort = null, $order = null, $offset = null, $limit = null)
    {

        if (!self::dataReady()) {
            $this->error('尚未建立数据表');
        }
        $map = array(
            'foreign.form_id' => $this->form['id'],
            'foreign.status' => 'normal',
        );
        $field = 'foreign.id,foreign.name';
        $columns = self::getFields();
        if (!empty($columns)) {
            foreach ($columns as $key => $value) {
                $field .= $key;
            }
        }

        $total = $this->model()->alias('data')
            ->join(config('database.prefix') . 'formdesign_foreign foreign', 'foreign.id = data.foreign_id')
            ->where($where)
            ->where($map)
            ->order($sort, $order)
            ->count();

        $list = $this->model()->alias('data')
            ->join(config('database.prefix') . 'formdesign_foreign foreign', 'foreign.id = data.foreign_id')
            ->where($where)
            ->where($map)
            ->order($sort, $order)
            ->limit($offset, $limit)
            ->select();

        $list = collection($list)->toArray();
        $result = array("total" => $total, "rows" => $list);
        return $result;
    }

    /**
     * 获取表单元素与数据字段关系
     * @return array
     */
    public function getFields(bool $query = false)
    {
        $data = unserialize($this->form['content_data']);
        $resule = [];
        $query_fields = explode(',', $this->form['query']);
        if (!empty($data)) {
            foreach ($data as $key => &$value) {
                if ($query) {
                    if (in_array($key, $query_fields)) {
                        $value['name'] = $key;
                        $resule[$key] = $value;
                    }
                } else {
                    $value['name'] = $key;
                    $resule[$key] = $value;
                }
            }
        }
        return $resule;
    }

    /**
     * 获取表单数据信息
     * @param string $id 数据ID
     * @return array
     */
    public function getForeign($id)
    {
        $foreign = \app\common\model\formdesign\Foreign::get($id);
        if (!$foreign) {
            $this->error('未找到数据，请返回重试!');
        }
        return $foreign;
    }

    /**
     * 获取指定标识的表单数据
     * @param string $id 数据ID
     * @return array
     */
    public function getData($id = null)
    {
        if ($id > 0) {
            $map = array(
                'foreign_id' => $id,
                'status' => 'normal',
            );
            $form_data = $this->model()
                ->where($map)
                ->find();
            if (!$form_data) {
                $this->error('未找到表单数据，请返回重试!');
            }
            return $form_data;
        } else {
            $this->error("参数错误");
        }
    }
    /**
     * 写入表单数据
     * @param array $data 数据
     * @param string $id 数据ID
     * @param string $name 数据名称，默认为时间+表单名称
     * @param string $data_id 相关数据ID
     * @return json
     */
    public function setData($data = [], $id = null, $name = null,$data_id=null)
    {
        if ($this->form['status'] !== 'normal') {
            $this->error('表单未启用!');
        }
        $trans = false;
        $unparse_data = $this->formdesign->unparse_data($this->form, $data);
        //新增
        if ($id == null) {
           // $foreign_name = $name != null ?: date('Y-m-d H:i', time()) . ':' . $this->form['form_name'];
           $foreign_name = $name != null ? $name: date('Y-m-d H:i', time()) . ':' . $this->form['form_name'];
            $foreign_model = new \app\common\model\formdesign\Foreign;
            $foreign_model->startTrans();
            //创建数据基础信息表
            $id = $trans = $foreign_model->save(['name' => $foreign_name, 'form_id' => $this->form['id'],'otherdataid'=>$data_id]);
            if ($trans) {
                $form_data = array_merge([
                    'uid' => 0,
                    'about_dataid'=>$data_id,
                    'createtime'=>time(),
                    'foreign_id' => $foreign_model->id,
                ], $unparse_data);
                $trans = $this->model($this->form['id'])->insert($form_data);
            }
            if ($id <= 0) {
                $foreign_model->rollback();
                $this->error('添加失败，请重试!');
            } else {
                $foreign_model->commit();
                $this->success('新增成功!');
            }
        }
        //修改
        else if ($id > 0) {
            $map = array(
                'foreign_id' => $id,              
                'status' => 'normal',
            );
            $data = array_merge(['uid' => 0], $unparse_data);
            $trans = $this->model()->where($map)->update($data);
          
            if ($trans) {
                $this->success('编辑成功!');
            } else {
                $this->error('编辑失败，请重试!');
            }
        }
    }
    /**
     * 写入表单查询字段
     * @param array $field 字段名，型如“data_1,data_2”
     * @return json
     */
    public function setQueryFields($field)
    {
        $query = implode(',', $field);
        $this->form->query = $query;
        if ($this->form->save()) {
            $this->success('设置成功');
        } else {
            $this->error("设置失败");
        }
    }
    /**
     * 返回表单查询字段
     * @return string
     */
    public function getQueryFields()
    {
        return $this->form['query'];
    }

}
